from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
from django.conf import settings
import base64
import os

from oauth.settings.base import BASE_DIR

class RsaCommon:

	def encrypt(self, message = ''):
		# 加载私钥用于加密
		recipient_key = RSA.import_key(open(os.path.abspath(BASE_DIR + "/rsa/rsa_public_key.pem")).read())
		cipher_rsa = PKCS1_v1_5.new(recipient_key)
		# 使用base64编码保存数据方便查看，同样解密需要base64解码
		en_data = base64.b64encode(cipher_rsa.encrypt(message.encode('utf-8')))
		#print("加密数据信息：", type(en_data), '\n', len(en_data), '\n', en_data)
		return en_data.decode("utf-8")


	def decrypt(self, en_data = ''):
		# 加载公钥用于解密
		encoded_key = open(os.path.abspath(BASE_DIR + "/rsa/rsa_private_key.pem")).read()
		private_key = RSA.import_key(encoded_key, passphrase="")
		cipher_rsa = PKCS1_v1_5.new(private_key)
		data = cipher_rsa.decrypt(base64.b64decode(en_data.encode("utf-8")), None)
		return data.decode("utf-8")

'''
if __name__ == '__main__':
	_rsa = RsaCommon()
	# 加密
	en_data = _rsa.encrypt("Loren ipsum")
	print("Encrypt: %s" % en_data)
	# 解密
	data = _rsa.decrypt(en_data)
	print("Decrypted: %s" % data)

	# 解密
	en_data = "egobA2GIUhuEPLOAm4C7uZjyolJ8Z+ePgL9FwsFrVmve8EZJCOB4MRlGffDMMRC3Diie2qEPLAfPPZuZBG537oL+PDmHvT7Dlam6DtQiGUJu+hpuoA31R6tS1dPdhmNal5DlmAw7toz7+lRN05HCWL6sLBuvpZmEZ/SoS/qtLBE3lZfFVVoNUAAxQc/G3ib9aFx0TaVu1hfSw3rb/DZL7JCA8n2VvOf5lWQP0y6c6kvf6JlFDcxd/UQsvWehJucXCNzZ5X2Pz68Yto20kejQO2LzCPnj2yf1yzN0XodyZ0UlY8r8Z6XyPPqxjhnokE3SuQCVF1bEnTR1s+7EAUrMvw=="
	data = _rsa.decrypt(en_data)
	print("Decrypted: %s" % data)
'''
